﻿using System;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using ParentChildLookup.Tools;
using ParentChildLookup.BO;

namespace ParentChildLookup.Controls
{
    public class LinkedLookupFieldIterator : ListFieldIterator
    {
        public ParentChildLookupBO parentChildLookup
        {
            get
            {
                string contentTypeId = this.GetContentTypeId();

                return SPTools.DeSerializeParentChildLookup(this.Web.Properties[contentTypeId]);
            }
        }
        protected override void CreateChildControls()
        {
            this.Controls.Clear();
            if (this.ControlTemplate == null)
            {
                throw new ArgumentException("Could not find ListFieldIterator control template.");
            }

            for (int i = 0; i < base.Fields.Count; i++)
            {
                SPField field = base.Fields[i];
                if (!this.IsFieldExcluded(field))
                {
                    CompositeField child = new CompositeField();
                    bool templateIsSet = false;
                    if (parentChildLookup != null)
                    {
                        if (field.InternalName == parentChildLookup.ParentFieldInternalName)
                        {
                            templateIsSet = true;
                            child.TemplateName = "ParentLookup";
                        }
                        else if (parentChildLookup.ChildFields.Contains(field.InternalName))
                        {
                            templateIsSet = true;
                            child.TemplateName = "ChildLookup";
                        }
                    }

                    if (!templateIsSet)
                        child.TemplateName = this.DefaultTemplateName;

                    child.ControlMode = base.ControlMode;
                    child.FieldName = field.InternalName;
                    this.Controls.Add(child);

                }
            }
        }
    }
}
